import React, { useState, useRef, useEffect } from 'react'
import { clsx } from 'clsx'
import { AIModel } from '../../services/aiService'
import { ChevronDownIcon, CheckIcon } from './Icon'

export interface ModelOption {
  id: AIModel
  name: string
  description: string
  features: string[]
  icon: string
  badge?: string
  color: string
}

// 免费AI模型选项配置
const freeModelOptions: ModelOption[] = [
  {
    id: 'doubao-seed-1-6-250615',
    name: '豆包 Seed-1.6',
    description: '字节跳动豆包模型，中文优化，多模态支持',
    features: ['中文优化', '多模态', '快速响应', '本土化'],
    icon: '🫘',
    badge: '推荐',
    color: 'orange'
  },
  {
    id: 'llama-3.1-70b-versatile',
    name: 'Llama 3.1 70B',
    description: 'Meta最新大模型，性能优秀',
    features: ['综合能力', '复杂推理', '代码生成'],
    icon: '🦙',
    badge: '免费',
    color: 'green'
  },
  {
    id: 'llama-3.1-8b-instant',
    name: 'Llama 3.1 8B',
    description: '轻量级模型，响应极速',
    features: ['超快速度', '日常对话', '快速回答'],
    icon: '⚡',
    badge: '极速',
    color: 'blue'
  },
  {
    id: 'mixtral-8x7b-32768',
    name: 'Mixtral 8x7B',
    description: 'Mistral混合专家模型',
    features: ['长上下文', '多语言', '专业分析'],
    icon: '🎯',
    badge: '32K',
    color: 'purple'
  }
]

// 传统模型选项（保留作为后备）
const legacyModelOptions: ModelOption[] = [
  {
    id: 'gpt-4',
    name: 'GPT-4',
    description: '最强大的通用模型',
    features: ['复杂推理', '代码生成', '创意写作'],
    icon: '🧠',
    badge: 'Plus',
    color: 'purple'
  },
  {
    id: 'gpt-3.5-turbo',
    name: 'GPT-3.5',
    description: '快速响应的标准模型',
    features: ['日常对话', '快速回答', '基础任务'],
    icon: '⚡',
    color: 'blue'
  },
  {
    id: 'claude-3-sonnet',
    name: 'Claude-3',
    description: '擅长分析和推理',
    features: ['深度分析', '逻辑推理', '文档理解'],
    icon: '🔍',
    color: 'green'
  }
]

// 默认使用免费模型
const modelOptions = freeModelOptions

interface ModelSelectorProps {
  currentModel: AIModel
  onModelChange: (model: AIModel) => void
  disabled?: boolean
  className?: string
}

export const ModelSelector: React.FC<ModelSelectorProps> = ({
  currentModel,
  onModelChange,
  disabled = false,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const currentModelOption = modelOptions.find(option => option.id === currentModel) || modelOptions[0]

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  return (
    <div className={clsx('relative', className)} ref={dropdownRef}>
      {/* 选择器按钮 */}
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className={clsx(
          'flex items-center space-x-3 px-4 py-3 rounded-xl transition-all duration-200',
          'border bg-white hover:bg-gray-50 focus:outline-none focus:ring-2',
          isOpen 
            ? 'border-blue-500 ring-2 ring-blue-100 shadow-lg' 
            : 'border-gray-200 hover:border-gray-300',
          disabled && 'opacity-50 cursor-not-allowed hover:bg-white hover:border-gray-200',
          'min-w-[200px] justify-between'
        )}
      >
        <div className="flex items-center space-x-3">
          <span className="text-lg">{currentModelOption.icon}</span>
          <div className="text-left">
            <div className="flex items-center space-x-2">
              <span className="font-medium text-gray-900">{currentModelOption.name}</span>
              {currentModelOption.badge && (
                <span className={clsx(
                  'text-xs px-1.5 py-0.5 rounded-full font-medium',
                  currentModelOption.color === 'purple' && 'bg-purple-100 text-purple-600',
                  currentModelOption.color === 'blue' && 'bg-blue-100 text-blue-600',
                  currentModelOption.color === 'green' && 'bg-green-100 text-green-600',
                  currentModelOption.color === 'gray' && 'bg-gray-100 text-gray-600'
                )}>
                  {currentModelOption.badge}
                </span>
              )}
            </div>
            <span className="text-xs text-gray-500">{currentModelOption.description}</span>
          </div>
        </div>
        <div className={clsx(
          'transform transition-transform duration-200 text-gray-400',
          isOpen ? 'rotate-180' : 'rotate-0'
        )}>
          <ChevronDownIcon size="sm" />
        </div>
      </button>

      {/* 下拉菜单 */}
      {isOpen && (
        <div className={clsx(
          'absolute top-full left-0 right-0 mt-2 bg-white border border-gray-200 rounded-xl shadow-xl z-50',
          'animate-fade-in origin-top'
        )}>
          <div className="p-2 space-y-1">
            {modelOptions.map((option) => (
              <button
                key={option.id}
                onClick={() => {
                  onModelChange(option.id)
                  setIsOpen(false)
                }}
                className={clsx(
                  'w-full flex items-start space-x-3 px-3 py-3 rounded-lg transition-all duration-200',
                  'hover:bg-gray-50 focus:outline-none focus:bg-gray-50',
                  currentModel === option.id && 'bg-blue-50 border border-blue-200'
                )}
              >
                <span className="text-lg mt-0.5">{option.icon}</span>
                <div className="flex-1 text-left">
                  <div className="flex items-center space-x-2 mb-1">
                    <span className="font-medium text-gray-900">{option.name}</span>
                    {option.badge && (
                      <span className={clsx(
                        'text-xs px-1.5 py-0.5 rounded-full font-medium',
                        option.color === 'purple' && 'bg-purple-100 text-purple-600',
                        option.color === 'blue' && 'bg-blue-100 text-blue-600',
                        option.color === 'green' && 'bg-green-100 text-green-600',
                        option.color === 'gray' && 'bg-gray-100 text-gray-600'
                      )}>
                        {option.badge}
                      </span>
                    )}
                    {currentModel === option.id && (
                      <div className="ml-auto">
                        <CheckIcon size="sm" className="text-blue-600" />
                      </div>
                    )}
                  </div>
                  <p className="text-xs text-gray-500 mb-2">{option.description}</p>
                  <div className="flex flex-wrap gap-1">
                    {option.features.map((feature, index) => (
                      <span 
                        key={index}
                        className="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded-full"
                      >
                        {feature}
                      </span>
                    ))}
                  </div>
                </div>
              </button>
            ))}
          </div>
          
          {/* 底部提示 */}
          <div className="border-t border-gray-100 px-4 py-3 bg-gray-50 rounded-b-xl">
            <p className="text-xs text-gray-500 text-center">
              选择最适合您需求的AI模型 · 可随时切换
            </p>
          </div>
        </div>
      )}
    </div>
  )
}

// 紧凑版模型选择器（用于顶部栏）
export const CompactModelSelector: React.FC<ModelSelectorProps> = ({
  currentModel,
  onModelChange,
  disabled = false,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const currentModelOption = modelOptions.find(option => option.id === currentModel) || modelOptions[0]

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  return (
    <div className={clsx('relative', className)} ref={dropdownRef}>
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className={clsx(
          'flex items-center space-x-2 px-3 py-2 rounded-lg transition-all duration-200',
          'text-sm font-medium border bg-white hover:bg-gray-50',
          isOpen 
            ? 'border-blue-500 ring-1 ring-blue-200' 
            : 'border-gray-200 hover:border-gray-300',
          disabled && 'opacity-50 cursor-not-allowed'
        )}
      >
        <span className="text-sm">{currentModelOption.icon}</span>
        <span className="text-gray-700">{currentModelOption.name}</span>
        {currentModelOption.badge && (
          <span className={clsx(
            'text-xs px-1.5 py-0.5 rounded-full font-medium',
            currentModelOption.color === 'purple' && 'bg-purple-100 text-purple-600',
            currentModelOption.color === 'blue' && 'bg-blue-100 text-blue-600',
            currentModelOption.color === 'green' && 'bg-green-100 text-green-600',
            currentModelOption.color === 'gray' && 'bg-gray-100 text-gray-600'
          )}>
            {currentModelOption.badge}
          </span>
        )}
        <div className={clsx(
          'text-gray-400 transition-transform duration-200',
          isOpen ? 'rotate-180' : 'rotate-0'
        )}>
          <ChevronDownIcon size="xs" />
        </div>
      </button>

      {isOpen && (
        <div className="absolute top-full right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-[180px]">
          <div className="p-1">
            {modelOptions.map((option) => (
              <button
                key={option.id}
                onClick={() => {
                  onModelChange(option.id)
                  setIsOpen(false)
                }}
                className={clsx(
                  'w-full flex items-center space-x-2 px-3 py-2 rounded-md transition-colors duration-200',
                  'hover:bg-gray-50 text-sm',
                  currentModel === option.id && 'bg-blue-50 text-blue-700'
                )}
              >
                <span>{option.icon}</span>
                <span className="flex-1 text-left">{option.name}</span>
                {option.badge && (
                  <span className={clsx(
                    'text-xs px-1.5 py-0.5 rounded-full font-medium',
                    option.color === 'purple' && 'bg-purple-100 text-purple-600',
                    option.color === 'blue' && 'bg-blue-100 text-blue-600',
                    option.color === 'green' && 'bg-green-100 text-green-600',
                    option.color === 'gray' && 'bg-gray-100 text-gray-600'
                  )}>
                    {option.badge}
                  </span>
                )}
                {currentModel === option.id && (
                  <CheckIcon size="xs" className="text-blue-600" />
                )}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}